#ifndef EQFREQDIAGRAM_H
#define EQFREQDIAGRAM_H

#include <QWidget>
#include <QPaintEvent>
#include <QPainter>
#include <QPainterPath>
#include <QMoveEvent>
#include <QWheelEvent>
#include <QDebug>

#include <vector>

#include "dm/dmstruct.h"
#include "dm/filter.h"


class Rectangle : public QObject
{
    Q_OBJECT
public:
    explicit Rectangle(const EQ &eq, QObject *parent = nullptr)
        : QObject{parent}
        , m_eq{eq}
        , m_parr{Filter::gainArray(eq)}
    {
        rect = QRectF(0, 0, 25, 25);
        lRect = rRect = QRectF(0, 0, 10, 10);
        txtRect = QRectF(0, 0, 400, 75);
        dragEnd();
    }
    ~Rectangle()
    {

    }
    EQ eq() const
    {
        return m_eq;
    }
    PairArray parr() const
    {
        return m_parr;
    }
    bool contains(const QPoint &p)
    {
        if (rect.contains(p)) {
            isDragging = true;
            return true;
        }
        else if (lRect.contains(p)) {
            isLDragging = true;
            return true;
        }
        else if (rRect.contains(p)) {
            isRDragging = true;
            return true;
        }
        return false;
    }
    void dragEnd()
    {
        isDragging = false;
        isLDragging = false;
        isRDragging = false;
    }
public slots:
    void setEq(const EQ &eq)
    {
        m_eq = eq;
        m_parr = Filter::gainArray(eq);
        emit stateChanged(number);
    }
    void move(const QPointF &p)
    {
        rect.moveCenter(p);
        lRect.moveCenter(QPointF(p.x() - EQ_BW_DEFAULT - m_eq.bw, p.y()));
        rRect.moveCenter(QPointF(p.x() + EQ_BW_DEFAULT + m_eq.bw, p.y()));
        txtRect.moveCenter(p);
    }
signals:
    void stateChanged(size_t);
public:
    bool isDragging;
    bool isLDragging;
    bool isRDragging;
    size_t number;
    QRectF rect;
    QRectF lRect;
    QRectF rRect;
    QRectF txtRect;
private:
    EQ m_eq;
    PairArray m_parr;
};


class EqFreqDiagram : public QWidget
{
    Q_OBJECT
public:
    explicit EqFreqDiagram(QWidget *parent = nullptr);
    ~EqFreqDiagram();
public slots:
    void setEqList(const QList<EQ> &list);
    void stateChanged(const int &number);
    void setArg(const int &index, const EQ &eq);
signals:
    void argChanged(const int &, const EQ &);
protected:

    void paintEvent(QPaintEvent *event) override;

    void mousePressEvent(QMouseEvent *event) override;

    void mouseMoveEvent(QMouseEvent *event) override;

    void mouseReleaseEvent(QMouseEvent *event) override;

private:
    QPainterPath getPath(const std::vector<QPointF> &vect) const;
    QPointF toPoint(const QRectF &rect, const double &freq, const double &gain) const;

    std::pair<double, double> toFreqAndGain(const QPointF &point) const;
private:
    QVector<Rectangle *> m_rects;
    int m_selectedIndex;
    QRectF m_cRect;
};

#endif // EQFREQDIAGRAM_H
